package com.store.app;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.recordBean_hy;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.store.app.activity.AccountCheckingActivity;
import com.store.app.activity.CashierActivity;
import com.store.app.activity.GoodsActivity;
import com.store.app.activity.HomeCaptureActivity;
import com.store.app.activity.MembersActivity;
import com.store.app.activity.MessageDispitchActivity;
import com.store.app.activity.PaymentActivity;
import com.store.app.activity.ScalePromotion_funActivity;
import com.store.app.activity.SetActivity;
import com.store.app.activity.SpecialSell_newActivity;
import com.store.app.activity.StoresActivity;
import com.store.app.activity.TaskActivity;
import com.store.app.activity.TheBuyOrderActivity;
import com.store.app.activity.TheSellOrderActivity;
import com.store.app.activity.WebViewBookedActivity;
import com.store.app.activity.WebViewHYDActivity;
import com.store.app.activity.WebViewLLMActivity;
import com.store.app.activity.WebViewMoreActivity;
import com.store.app.activity.WebViewTGActivity;
import com.store.app.bean.CouponUpdateBean;
import com.store.app.bean.HomeDotBean;
import com.store.app.http.Stores;
import com.store.app.hyphenate.HyphenateHelper;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.utils.TestDeviveInfo;
import com.store.app.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

/**
 * 主页
 */
public class FunctionHighActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {

    private TextView tvSet;//设置
    private TextView tvTitle;//标题
    private ImageView message;//消息
    private ImageView message_dot;//消息红点(表示有未读消息)
    private TextView cash_one;//扫一扫
    private TextView cash_two;//收款码
    private TextView cash_three;//收银台

    private TextView cash;//卖单
    private RelativeLayout order;//买单
    TextView about;//店铺
    private RelativeLayout rl_task;//任务
    TextView ll_task;//任务(文本)
    TextView type_goods;//商品
    TextView wallet;//账户

    private TextView members;//会员
    private TextView sales_promotion;//促销
    private TextView inventory;//盘点

    private TextView huiyiding;//惠易定
    private TextView wyp;//我要批
    private TextView llShequ;//淘淘领

    private TextView community;//特卖
    TextView llDaiban;//推广
    TextView exchange;//更多

    private TextView tvSellNumber;
    private ImageView task_dot;//任务红点


    private NetRequest netRequest;
    private boolean isNeedUpdate;
    private AlertDialog imageDialog;

    SharedPreferences preferences;
    //是否登录跳转过来的
    private boolean islogintent = false;

    //数据库存储
    private DBHelper_hy db = null;
    private recordBean_hy rb = null;

    static {
        System.loadLibrary("iconv");
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String info = TestDeviveInfo.getDeviceInfo(this);//未用
        netRequest = new NetRequest(this);
        islogintent = getIntent().getBooleanExtra("islogintent", false);
        if (!islogintent) {
            Log.i("mylog", "功能页面检查版本");
            netRequest.requestCheckVersion(4);
        }

        if (db == null) {
            db = new DBHelper_hy(this);
            rb = new recordBean_hy();
        }
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        Log.v("zyl", "M:" + MainActivity.member_id);
        Log.v("zyl", "M:" + MainActivity.user_security_code);
        Log.v("zyl", "M:" + MainActivity.user_token);

        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.function_high);

        //获取个人登陆资料
        getPerInfo();
        initView();
        ExitApplication.getInstance().addActivity(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //查询资产信息
        if (!TextUtils.isEmpty(MainActivity.app_token) && !TextUtils.isEmpty(MainActivity.member_id)) {
            netRequest.requestQueryAccount(2);
        }
        //查询促销规则
        netRequest.requestStoreActivityPaymentFind(5);
//        //检查是否有群崩溃id
//        String live_room_id = preferences.getString("live_room_id", "");
//        if (!TextUtils.isEmpty(live_room_id)) {
//            netRequest.requestHXCloseOneLiveRoom(6, LocationApplication.im_user_id, live_room_id);
//            preferences.edit().putString("live_room_id", "").apply();
//        }

        //算出屏幕宽高度，保存起来，后面有用
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        SettingData.SCREEN_WIDTH = width;
        SettingData.SCREEN_HEIGHT = height;

//        Intent intent = new Intent(this,GoodReplenishmentActivity.class);
//        intent.putExtra("zbm","1");
//        intent.putExtra("barcode","1");
//        intent.putExtra("goods_name","1");
//        intent.putExtra("price","1");
//        intent.putExtra("price_specifications","1");
//        intent.putExtra("purchase_price_specifications","1");
//        intent.putExtra("unit","1");
//        intent.putExtra("bzq","1");
//        intent.putExtra("pcm","1");
//        intent.putExtra("clw","1");
//        startActivity(intent);
//        netRequest.requestSpecificationUnitFind(1);
//        try {
//            JSONArray jsonArray = new JSONArray();
//            JSONObject jsonObject = new JSONObject();
//            JSONObject jsonObject2 = new JSONObject();
//            jsonObject.put("path", "xxxx");
//            jsonObject2.put("path", "3333x");
//            jsonArray.put(jsonObject);
//            jsonArray.put(jsonObject2);
//            Log.v("zyl", "jsonArray:" + jsonArray.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //是否显示消息红点
        if (preferences != null) {
            int i_mainmess = preferences.getInt("mainmess", 0);
            if (i_mainmess == 1) {
                message_dot.setVisibility(View.VISIBLE);
            } else {
                if (message_dot.getVisibility() == View.VISIBLE) {
                    message_dot.setVisibility(View.INVISIBLE);
                }
            }
        }
        EventBus.getDefault().register(this);
    }
    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);

        super.onDestroy();

    }

    public void onRefresh(CouponUpdateBean event) {
        //卖单红点数据修改
        if (event.type == 99) {
            if (event.number.equals("0")) {
                tvSellNumber.setVisibility(View.GONE);
            } else {
                tvSellNumber.setVisibility(View.VISIBLE);
                tvSellNumber.setText(event.number);
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        netRequest.requestOrderCount(1);//查询便利店订单数量(卖单数量)
        netRequest.requestTaskNumber(6);//查询任务数量

    }

    private void getPerInfo() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (TextUtils.isEmpty(MainActivity.app_token)) {
            String s_app_token = preferences.getString(MainActivity.PREF_APP_TOKEN, null);
            if (!TextUtils.isEmpty(s_app_token)) {
                MainActivity.app_token = s_app_token;
            }
        }
        if (TextUtils.isEmpty(MainActivity.security_code)) {
            String s_security_code = preferences.getString(MainActivity.PREF_SECURITY_CODE, null);
            if (!TextUtils.isEmpty(s_security_code)) {
                MainActivity.security_code = s_security_code;
            }
        }
        if (TextUtils.isEmpty(MainActivity.user_token)) {
            String s_user_token = preferences.getString(MainActivity.PREF_USER_TOKEN, null);
            if (!TextUtils.isEmpty(s_user_token)) {
                MainActivity.user_token = s_user_token;
            } else {
            }
        } else {
        }
        if (TextUtils.isEmpty(MainActivity.user_security_code)) {
            String s_user_security_code = preferences.getString(MainActivity.PREF_USER_SECURITY_CODE, null);
            if (!TextUtils.isEmpty(s_user_security_code)) {
                MainActivity.user_security_code = s_user_security_code;
            }
        } else {
        }
        if (TextUtils.isEmpty(MainActivity.member_id)) {
            String s_member_id = preferences.getString(MainActivity.PREF_MEMBER_ID, null);
            if (!TextUtils.isEmpty(s_member_id)) {
                MainActivity.member_id = s_member_id;
            }
        } else {
        }
        if (TextUtils.isEmpty(MainActivity.is_admin)) {
            String s_is_admin = preferences.getString(MainActivity.PREF_IS_ADMIN, null);
            if (!TextUtils.isEmpty(s_is_admin)) {
                MainActivity.is_admin = s_is_admin;
            }
        }
        //获取本地店铺信息
        new Stores(MainActivity.app_token, MainActivity.member_id, FunctionHighActivity.this).setDatabase();
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        Log.v("zyl", "onExecuteSuccess:" + result);
        //查询未读消息数量
        if (requestId == 1) {
            try {
                JSONObject data = new JSONObject(result);
                String count_num = data.getString("count_num");
                onRefresh(new CouponUpdateBean(99, count_num));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //查询资产信息成功 零钱、礼券、金币
        else if (requestId == 2) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                int vo = Integer.parseInt(jsonObject.getString("voucher_balance"));
                double banlance = Double.parseDouble(jsonObject.getString("cash_balance"));
                Stores.cash_balance = banlance;
                Stores.voucher_balance = vo;
                Stores.gold = jsonObject.getString("gold");
                //在其他地方重连的时候这个地方链接环信
                if (!EMClient.getInstance().isLoggedInBefore() || !EMClient.getInstance().isConnected()) {
                    if (islogintent) {
                        islogintent = false;
                    } else {
                        String im_id = preferences.getString("im_user_id", "");
                        if (!TextUtils.isEmpty(im_id)) {
                            Log.i("mylog", "重连环信");
                            login(im_id);
                        }
                    }
                }
            } catch (Exception e) {
            }
        } else if (requestId == 4) {//检测版本更新
            try {
                JSONObject jsonObjectData = new JSONObject(result);
                int version_code = jsonObjectData.getInt("version_code");
                String version_name = jsonObjectData.getString("version_name");
                final String download_path = jsonObjectData.getString("download_path");
                final String update_content = jsonObjectData.getString("update_content");
                PackageManager pm = FunctionHighActivity.this.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(FunctionHighActivity.this.getPackageName(), 0);
                int currentVersionCode = pi.versionCode;
                Log.v("zyl", "当前的版本号为：" + currentVersionCode);
                Log.v("zyl", "服务器的版本号为：" + version_code);
                if (currentVersionCode < version_code) {
                    isNeedUpdate = true;
                    imageDialog = new AlertDialog.Builder(FunctionHighActivity.this).setTitle("发现新版本!是否立即更新?").setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.v("zyl", "download_path:" + download_path);
                            if (!TextUtils.isEmpty(download_path)) {
                                if (isDownloadManagerAvailable(FunctionHighActivity.this)) {
                                    Log.v("zyl", "下载器可用");
                                    downLoadPackage(download_path);
                                } else {
                                    doShequClick(download_path);
                                }
                            } else {
                                ToastTools.showShort(FunctionHighActivity.this, "下载地址无效!");
                            }
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ToastTools.showShort(FunctionHighActivity.this, "当前版本不再支持,请更新到最新版本!");
                            finish();
                        }
                    }).setMessage("更新内容：\n" + update_content).show();

                    imageDialog.setCancelable(false);


                    Log.v("zyl", "当前的版本号小于服务器的版本号,需要更新");

//                Uri uri = Uri.parse(download_path);
//                Intent viewIntent = new Intent(Intent.ACTION_VIEW,uri);
//                WebViewActivity.this.startActivity(viewIntent);
                } else {
                    Log.v("zyl", "当前的版本已经是最新版本");
                }
            } catch (Exception e) {
            }
        } else if (requestId == 5) { //查询促销规则
            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String activity = jsonObject.getString("activity");
                    //满返
                    if (activity.equals("rebate")) {
                        SettingData.moreRebate = jsonObject.getString("amount");
                        SettingData.moreRebateData = jsonObject.getString("promotion");
                        SettingData.rebateStatus = jsonObject.getString("status");
                    }
                    //折扣
                    if (activity.equals("discount")) {
                        SettingData.discount = jsonObject.getString("promotion");
                        SettingData.discountStatus = jsonObject.getString("status");
                    }
                    //满送
                    if (activity.equals("reward")) {
                        SettingData.moreReward = jsonObject.getString("amount");
                        SettingData.moreRewardData = jsonObject.getString("promotion");
                        SettingData.rewardStatus = jsonObject.getString("status");
                    }
                }
            } catch (Exception e) {
            }
        } else if (requestId == 6) {//查询任务数量
            try {
                JSONObject jsonObject = new JSONObject(result);
                String task_count = jsonObject.getString("task_count");
                if (task_count.equals("0")) {//控制任务红点的显示和隐藏
                    task_dot.setVisibility(View.INVISIBLE);
                } else {
                    task_dot.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.v("zyl", "onExecuteFail:" + msg);
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(Stores.stores_name);
        //领了么==>淘淘领
        llShequ = (TextView) findViewById(R.id.ll_shequ);
        //跳转到淘淘领首页(WebView)
        llShequ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                doShequClick();
                MobclickAgent.onEvent(FunctionHighActivity.this, "025");
                Intent intent7 = new Intent();
                intent7.setClass(FunctionHighActivity.this, WebViewLLMActivity.class);
                intent7.putExtra("title", "淘淘领"); //领了么==>淘淘领
                intent7.putExtra("from", "cjf");
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(FunctionHighActivity.this);
                String login_phone = preferences.getString("login_phone", "");
                intent7.putExtra("url", SettingData.http + SettingData.mflURL + Stores.area_id + "&mi=" + MainActivity.member_id + "&mobile=" + login_phone + "&stores_name=" +
                        Stores.stores_name + "&contact_person=" + Stores.contact_person + "&bind=1");//领了么首页url添加参数bind=1

                startActivity(intent7);
            }
        });
        //卖单
        cash = (TextView) findViewById(R.id.cash);
        cash.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "023");
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, TheSellOrderActivity.class);
                startActivity(intent);
            }
        });
        //我要批
        wyp = (TextView) findViewById(R.id.fun_wyp);
        wyp.setOnClickListener(this);
        //扫一扫
        cash_one = (TextView) findViewById(R.id.cash_one);
        cash_one.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "018");
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, HomeCaptureActivity.class);
                startActivity(intent);

            }
        });
        //收款码
        cash_two = (TextView) findViewById(R.id.cash_two);
        cash_two.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "014");
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, PaymentActivity.class);
                startActivity(intent);
            }
        });

        //特卖
        community = (TextView) findViewById(R.id.fun_shequ);
        community.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "026");
                Intent intent = new Intent(FunctionHighActivity.this, SpecialSell_newActivity.class);
                startActivity(intent);
            }
        });

        //推广
        llDaiban = (TextView) findViewById(R.id.ll_daiban);
        llDaiban.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "027");
                //跳转到推广页面(WebView)
                Intent intent6 = new Intent();
                intent6.setClass(FunctionHighActivity.this, WebViewTGActivity.class);
                intent6.putExtra("title", "推广");
                intent6.putExtra("url", SettingData.http + SettingData.tuiguangURL + MainActivity.member_id);
//                intent6.putExtra("url", "https://fan.meitianhui.com/fan");
                startActivity(intent6);
            }
        });

        //设置
        tvSet = (TextView) findViewById(R.id.set);
        tvSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "029");
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, SetActivity.class);
                startActivity(intent);
            }
        });
        //任务
        ll_task = (TextView) findViewById(R.id.ll_task);
        ll_task.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, TaskActivity.class);
                startActivity(intent);
            }
        });
        //促销
        sales_promotion = (TextView) findViewById(R.id.sales_promotion);
        sales_promotion.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "006");
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, ScalePromotion_funActivity.class);
                startActivity(intent);
            }
        });
        //商品
        type_goods = (TextView) findViewById(R.id.type_goods);
        type_goods.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "003");
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, GoodsActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
            }
        });
        //盘点
        inventory = (TextView) findViewById(R.id.inventory);
        inventory.setOnClickListener(this);
        //更多
        exchange = (TextView) findViewById(R.id.exchange);
        exchange.setOnClickListener(this);
        //账户
        wallet = (TextView) findViewById(R.id.wallet);
        wallet.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "005");
                Intent intent0 = new Intent();
                intent0.setClass(FunctionHighActivity.this, AccountCheckingActivity.class);
                startActivity(intent0);
            }
        });

        //店铺
        about = (TextView) findViewById(R.id.about);
        about.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "002");
                Intent intent4 = new Intent();
                intent4.setClass(FunctionHighActivity.this, StoresActivity.class);
                startActivity(intent4);

            }
        });
        //会员
        members = (TextView) findViewById(R.id.ll_family_card);
        members.setOnClickListener(this);
        //消息
        message = (ImageView) findViewById(R.id.message);
        message.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "015");
                if (Utils.isFastClick()) {
                    return;
                }
                //消息红点消失
                if(message_dot.getVisibility()==View.VISIBLE) {
                    message_dot.setVisibility(View.INVISIBLE);
                    if (preferences!= null) {
                        preferences.edit().putInt("mainmess", 0).apply();
                    }
                }
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, MessageDispitchActivity.class);
                startActivity(intent);
//                }else{
//                    //登录环信
//                    netRequest.requestHXIMUserLogin(3, MainActivity.member_id, "stores", Stores.stores_name,"");
//                }
//                }catch (Exception e){}
            }
        });

        //买单
        order = (RelativeLayout) findViewById(R.id.order);
        order.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                MobclickAgent.onEvent(FunctionHighActivity.this, "024");
                Intent intent = new Intent(FunctionHighActivity.this, TheBuyOrderActivity.class);
                startActivity(intent);
            }
        });
        //惠易定
        huiyiding = (TextView) findViewById(R.id.huiyiding);
        huiyiding.setOnClickListener(this);
        tvSellNumber = (TextView) findViewById(R.id.tv_sell_number);
        if (tvSellNumber.getText().toString().trim().equals("0")) {
            tvSellNumber.setVisibility(View.GONE);
        }
        message_dot = (ImageView) findViewById(R.id.message_dot);
        cash_three = (TextView) findViewById(R.id.cash_three);
        cash_three.setOnClickListener(this);
        task_dot = (ImageView) findViewById(R.id.task_dot);
        rl_task = (RelativeLayout) findViewById(R.id.rl_task);
        rl_task.setOnClickListener(this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exitBy2Click();
            // 调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一下退出应用", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            ExitApplication.getInstance().exit();
        }
    }

    public static Toast toast = null;
    public static int LENGTH_LONG = Toast.LENGTH_LONG;
    private static int LENGTH_SHORT = Toast.LENGTH_SHORT;
    private static Context context = null;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //收银台
            case R.id.cash_three:
                MobclickAgent.onEvent(FunctionHighActivity.this, "001");
                Intent intentCash = new Intent();
                intentCash.setClass(FunctionHighActivity.this, CashierActivity.class);
                startActivity(intentCash);
                break;

            //我要批
            case R.id.fun_wyp:
                MobclickAgent.onEvent(FunctionHighActivity.this, "012");
                //跳转到我要批(WebView页面)
                Intent intent = new Intent();
                intent.setClass(FunctionHighActivity.this, WebViewBookedActivity.class);
                intent.putExtra("from", "wyp");//如果是我要批页面跳过去又上角是搜索
                intent.putExtra("url", SettingData.http + SettingData.wypURL + Stores.area_id);
                intent.putExtra("title", "我要批");
                startActivity(intent);
                break;
            //会员
            case R.id.ll_family_card:
                MobclickAgent.onEvent(FunctionHighActivity.this, "020");
                Intent intent2ActiveFamilyActivity = new Intent(FunctionHighActivity.this, MembersActivity.class);
                startActivity(intent2ActiveFamilyActivity);
                break;
            //惠易定
            case R.id.huiyiding:
                MobclickAgent.onEvent(FunctionHighActivity.this, "013");
                Intent intent4 = new Intent();
                intent4.setClass(FunctionHighActivity.this, WebViewHYDActivity.class);
                intent4.putExtra("title", "惠易定");
                intent4.putExtra("url", SettingData.hydURL + "/checklogin?channel=android&isAdmin=" + MainActivity.is_admin);
//                intent4.putExtra("url", "http://s.meitianhui.com/wap/");
//                intent4.putExtra("url", "http://dtest.meitianhui.com/wap/hyd/convenient-store/register.html");
                startActivity(intent4);
                break;
            //盘点
            case R.id.inventory:
                MobclickAgent.onEvent(FunctionHighActivity.this, "009");
                Intent intent5 = new Intent();
                intent5.setClass(FunctionHighActivity.this, WebViewTGActivity.class);
                intent5.putExtra("title", "盘点");
                intent5.putExtra("url", SettingData.http + SettingData.pandianURL + MainActivity.member_id);
                startActivity(intent5);
                break;
            //更多
            case R.id.exchange:
                MobclickAgent.onEvent(FunctionHighActivity.this, "028");
//                ToastTools.showShort(FunctionHighActivity.this,"暂未开放，敬请期待！");
                Intent intent8 = new Intent();
                intent8.setClass(FunctionHighActivity.this, WebViewMoreActivity.class);
                intent8.putExtra("title", "更多");
                intent8.putExtra("url", SettingData.http + SettingData.moreURL + MainActivity.member_id);
//                intent8.putExtra("url", "https://fan.meitianhui.com/fan");
                startActivity(intent8);
                break;
            default:
                break;
        }
    }

    public void doShequClick(final String downloadurl) {

        try {
            Uri uri = Uri.parse(downloadurl);
            Intent browserIntent = new Intent(Intent.ACTION_VIEW);
            browserIntent.setDataAndType(uri, "text/html");
            browserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            startActivity(browserIntent);
            finish();
        } catch (Exception e) {
            Toast.makeText(FunctionHighActivity.this, "请到腾讯应用宝更新最新安装包!", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    public void login(final String s_name) {
        EMClient.getInstance().login(s_name, s_name, new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.v("zyl", "登录环信成功");
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d("mylog", "login: " + progress);
            }

            @Override
            public void onError(final int code, final String message) {
                Log.v("zyl", s_name + "登录环信失败:" + message);
                loginAgain(s_name);
            }
        });
    }

    //登录错误的情况下先调退出接口再登录一次
    public void loginAgain(final String s_name) {
        HyphenateHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                EMClient.getInstance().login(s_name, s_name, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        Log.i("zyl", "再次登录环信成功");
                        // ** manually load all local groups and conversation
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();

                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {

            }
        });

    }
    //有消息过来的eventbus
    public void onEventMainThread(HomeDotBean bean){
        if(bean.type==1){
            try {
                if (message_dot.getVisibility()==View.INVISIBLE) {
                    message_dot.setVisibility(View.VISIBLE);
                }
            }catch (Exception e){

            }
        }
    }
}
